package com.sunday.common.sharding.sphere.jdbc.study.base.sync.obj;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: zsy
 * @Create: 2023/4/4 15:13
 */
public class SynchronizeAndObjectLock2 {

    /**
     * synchronized分别修饰同一个类对象的非静态方法和当前对象时互斥
     *
     * 【结论】snchronized修饰非静态方法与synchronized(this)互斥，可见，snchronized修饰非静态方法实质锁的是当前对象。
     */
    public static void main(String[] args) throws Exception {
        // 【注意】当且仅当是同一个SynchronizeAndObjectLock2对象
        SynchronizeAndObjectLock2 synchronizeAndObjectLock2 = new SynchronizeAndObjectLock2();
        new Thread(() -> {
            synchronizeAndObjectLock2.test1();
        }).start();

        new Thread(() -> {
            synchronizeAndObjectLock2.test2();
        }).start();
    }

    public void test1() {

        synchronized (this) {
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
            }
            System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
        }

    }

    public synchronized void test2() {

        System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (Exception e) {
        }
        System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
    }

}
